package ui.fragment.PosControl;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.R;
import net.ck.hzq.TobuyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import activity.SelectFlowPartnerActivity;
import base.BaseBiz;
import base.LazyFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.OnLoadMoreListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.RecyclerViewFinal;
import dao.DirectionalDevicesInput;
import dialog.DirectionalAllocationDialog;
import dialog.DirectionalAllocationFalseDialog;
import dialog.DirectionalAllocationResDialog;
import event.DefaultAddressEvent;
import event.DirectionalResEvent;
import event.NetErrorEvent;
import event.PosAllotEvent;
import event.PosSearchEvent;
import event.PushBackEvent;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import ui.activity.poscontrol.adapter.NotActiveAdapter;
import ui.activity.poscontrol.beanmodel.MyPosBean;
import ui.activity.poscontrol.beanmodel.PosInfoBean;
import ui.activity.poscontrol.biz.MyPosControlBiz;
import ui.activity.poscontrol.component.DaggerMyPosControlComponent;
import ui.activity.poscontrol.contract.MyPosControlContract;
import ui.activity.poscontrol.module.MyPosControlModule;
import ui.activity.poscontrol.presenter.MyPosControlPresenter;

/**
 * Created by fangjunsong on 2019年3月19日17:03:30.
 * <p>
 * 未激活
 */

public class NotActiveFra extends LazyFragment implements MyPosControlContract.View {


    @Inject
    MyPosControlPresenter presenter;
    @Inject
    MyPosControlBiz biz;


    @BindView(R.id.pull_refresh_rv)
    RecyclerViewFinal rv;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.fanxianfanwei_linear)//返现范围排序linear
            LinearLayout fanxianfanwei_linear;
    @BindView(R.id.youxiaoqi_linear)//有效期排序Linear
            LinearLayout youxiaoqi_linear;
    @BindView(R.id.fanxianfanwei_image)//返现范围排序小箭头图标
            ImageView fanxianfanwei_image;
    @BindView(R.id.youxiaoqi_image)//有效期排序小箭头图标
            ImageView youxiaoqi_image;
    @BindView(R.id.piliangchuli_text)//批量处理按钮
            TextView piliangchuli_text;
    @BindView(R.id.select_push_image)//选择是直接划拨还是定向划拨
            ImageView select_push_image;
    @BindView(R.id.return_amount_et)//划拨金额输入框
            AppCompatEditText return_amount_et;
    @BindView(R.id.flow_btn)//划拨按钮
            TextView flow_btn;

    @BindView(R.id.total_count)//全部终端数量
            TextView total_count;

    @BindView(R.id.selected_count)//已选择的终端数量
            TextView selected_count;
    double moneyMax = 0;
    private int pushtype = 0;//0直接划拨，1定向划拨
    private int youxiaoqiType = 0;//0默认,1从高到低,2从低到高
    private int fanxianType = 0;//0默认,1从高到低,2从低到高
    private String desc = "";//倒序字段{"expire_time":有效期排序, "back_amount":"返现金额"}
    private String asc = "";//正序字段{"expire_time":有效期排序, "back_amount":"返现金额"}
    NotActiveAdapter adp;
    private boolean isPrepared;// 界面否
    private boolean isALeady = true;
    private SharedPreferences sp;
    public List<String> mSelectedDevices = new ArrayList<>();
    private int mMaxBackAmount;
    AlertDialog updateDialog;
    List<MyPosBean.RecordsBean> totalbean= new ArrayList<>();
    List<MyPosBean.RecordsBean> clonetotal = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.not_active_layout, container, false);
        ButterKnife.bind(this, view);
        DaggerMyPosControlComponent.builder().myPosControlModule(new MyPosControlModule(this)).build().inject(this);
        presenter.setBiz(biz);
        sp = getActivity().getSharedPreferences("ToBuy", Context.MODE_PRIVATE);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.setItemAnimator(new DefaultItemAnimator());
        rv.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        rv.setNoLoadMoreHideView(true);
        rv.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                presenter.getUnActiveList(TobuyApplication.getCustomId(), false, desc, asc);
            }
        });
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptr.onRefreshComplete();
            }
        });


        RxView.clicks(piliangchuli_text)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> piLiangChuLi());
        RxView.clicks(select_push_image)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> selectPush());

//        RxView.clicks(youxiaoqi_linear)
//                .compose(this.<Void>bindToLifecycle())
//                .throttleFirst(500, TimeUnit.MILLISECONDS)
//                .subscribe(Void ->selectYouXiaoQi());
        RxView.clicks(fanxianfanwei_linear)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> selectFanXian());
        RxView.clicks(flow_btn)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> goPush());
        presenter.getUnActiveList(TobuyApplication.getCustomId(), true, desc, asc);
        return view;
    }

    @Override
    protected void lazyLoad() {
        if (isPrepared && isVisible && isALeady) {
            // TODO 在这里处理逻辑
            isALeady = false;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void PosSearchEvent(PosSearchEvent event) {
        clonetotal.clear();

        for (int i = 0;i<totalbean.size();i++){
            if(totalbean.get(i).getSn().contains(event.getPossn())){
                clonetotal.add(totalbean.get(i));
            }
        }
        adp.notifyDataSetChanged();
//            adp = new NotActiveAdapter(getActivity(), clonetotal);
//            rv.setAdapter(adp);
    }
    public void piLiangChuLi() {
        if (!TobuyApplication.isPiliang) {
            piliangchuli_text.setBackgroundResource(R.mipmap.morechangeyes);
            TobuyApplication.isPiliang = true;
        } else {
            piliangchuli_text.setBackgroundResource(R.mipmap.morechangeno);
            TobuyApplication.isPiliang = false;
        }
    }

    public void selectPush() {
        if (pushtype == 0) {
            select_push_image.setBackgroundResource(R.mipmap.dingxianghuabo);
            pushtype = 1;
        } else {
            select_push_image.setBackgroundResource(R.mipmap.zhijiehuabo);
            pushtype = 0;
        }
    }

    public void selectYouXiaoQi() {
        fanxianfanwei_image.setBackgroundResource(R.mipmap.morensearch);

        if (youxiaoqiType == 0 || youxiaoqiType == 2) {
            youxiaoqi_image.setBackgroundResource(R.mipmap.topsearch);
            youxiaoqiType = 1;
            asc = "expire_time";
            desc = "";
            presenter.getUnActiveList(TobuyApplication.getCustomId(), true, "", asc);
        } else {
            youxiaoqi_image.setBackgroundResource(R.mipmap.downsearch);
            youxiaoqiType = 2;
            desc = "expire_time";
            asc = "";
            presenter.getUnActiveList(TobuyApplication.getCustomId(), true, desc, "");
        }

    }

    public void selectFanXian() {
        youxiaoqi_image.setBackgroundResource(R.mipmap.morensearch);
        if (fanxianType == 0 || fanxianType == 2) {
            fanxianfanwei_image.setBackgroundResource(R.mipmap.topsearch);
            fanxianType = 1;
            asc = "back_amount";
            desc = "";
            presenter.getUnActiveList(TobuyApplication.getCustomId(), true, "", asc);
        } else {
            fanxianfanwei_image.setBackgroundResource(R.mipmap.downsearch);
            fanxianType = 2;
            desc = "back_amount";
            asc = "";
            presenter.getUnActiveList(TobuyApplication.getCustomId(), true, desc, "");
        }

    }

    public void goPush() {
        if (mSelectedDevices.size() == 0) {
            Toast.makeText(getActivity(), "请选择至少一台终端", Toast.LENGTH_SHORT).show();
            return;
        }

//        if (TextUtils.isEmpty(return_amount_et.getEditableText())) {
//            Toast.makeText(getActivity(), "请设置返现金额", Toast.LENGTH_SHORT).show();
//            return;
//        }

//        if (Integer.valueOf(return_amount_et.getEditableText().toString()) > mMaxBackAmount) {
//            Toast.makeText(getActivity(), "返现金额的设置范围不得高于本级返现金额", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (pushtype == 0) {
            SelectFlowPartnerActivity.start(getActivity(), 11);
        } else {
            showdialog();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onPushBackEvent(PushBackEvent event) {
        presenter.flowDevices(Integer.valueOf(event.partnerId), mSelectedDevices,0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        presenter.getUnActiveList(TobuyApplication.getCustomId(), true, desc, asc);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        biz.onDestory();
        ButterKnife.bind(getActivity()).unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }


    @Override
    public void upDateUI(MyPosBean infoBean, List<MyPosBean.RecordsBean> bean, boolean refresh) {
        totalbean = bean;
        clonetotal.addAll(totalbean);
        total_count.setText("终端数量：" + infoBean.getTotal() + "台");

        if (moneyMax == 0) {
            for (int i = 0; i < bean.size(); i++) {
                if (moneyMax < bean.get(i).getBackAmount()) {
                    moneyMax = bean.get(i).getBackAmount();
                }
            }
            return_amount_et.setHint("当前可设置范围0-" + (int) moneyMax + "元/台");
        }

        if (adp == null) {
            adp = new NotActiveAdapter(getActivity(), clonetotal);
            rv.setAdapter(adp);
        } else {
            if (refresh) {
                adp.refresh();
            }
            adp.notifyDataSetChanged();
        }
    }

    @Override
    public void upDateInfoListUI(PosInfoBean infoBean, List<PosInfoBean.RecordsBean> bean) {

    }

    @Override
    public void refreshComplete() {
        ptr.onRefreshComplete();
    }

    @Override
    public void refreshData() {
        youxiaoqi_image.setBackgroundResource(R.mipmap.morensearch);
        fanxianfanwei_image.setBackgroundResource(R.mipmap.morensearch);
        presenter.getUnActiveList(TobuyApplication.getCustomId(), true, "", "");
        return_amount_et.setText("");
    }


    @Override
    public void loadMoreComplete() {
        rv.onLoadMoreComplete();
    }

    @Override
    public void hasLoadMore(boolean b) {
        rv.setHasLoadMore(b);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(PosAllotEvent event) {
        return_amount_et.setHint("当前可设置范围0-" + event.mMaxBackAmount + "元/台");
        mMaxBackAmount = event.mMaxBackAmount;
        mSelectedDevices.clear();
        mSelectedDevices.addAll(event.mSelectedDevices);
        selected_count.setText("已选择：" + mSelectedDevices.size() + "台");
    }

    private void showdialog() {
        DirectionalAllocationDialog dialog = DirectionalAllocationDialog.newInstance();
        dialog.setConfirmListener((String name, String tel) -> {

            dialog.dismiss();
            DirectionalDevicesInput a = new DirectionalDevicesInput();
            a.backAmount = return_amount_et.getText().toString();
            a.fromId = TobuyApplication.getCustomId();
            a.toName = name;
            a.toPhone = tel;
            a.snList = new String[mSelectedDevices.size()];
            for (int i = 0; i < mSelectedDevices.size(); i++) {
                a.snList[i] = mSelectedDevices.get(i);
            }
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(a));
            biz.Directionalallocation(requestBody, new BaseBiz.Callback<Boolean>() {
                @Override
                public void onSuccess(Boolean info) {
                    DirectionalAllocationResDialog dialogOK = DirectionalAllocationResDialog.newInstance();
                    dialogOK.setConfirmListener(() -> {
                        dialogOK.dismiss();
                        EventBus.getDefault().post(new DirectionalResEvent());
                    });
                    dialogOK.show(getFragmentManager(), "");
                    youxiaoqi_image.setBackgroundResource(R.mipmap.morensearch);
                    fanxianfanwei_image.setBackgroundResource(R.mipmap.morensearch);
                    presenter.getUnActiveList(TobuyApplication.getCustomId(), true, "", "");
                    return_amount_et.setText("");
                }

                @Override
                public void onFailure(Boolean info) {
                    DirectionalAllocationFalseDialog dialogFALSE = DirectionalAllocationFalseDialog.newInstance();
                    dialogFALSE.setConfirmListener(() -> {
                        dialogFALSE.dismiss();
                        showdialog();
                    });
                    dialogFALSE.show(getFragmentManager(), "");

                }
            });
        });
        dialog.show(getFragmentManager(), "");
    }

}
